﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using NetTaste;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TReceivingOrderDetailRepository : BaseRepository<TReceivingOrderDetail>, ITReceivingOrderDetailRepository
    {
        private readonly IBarCodeRuleRepository _BarCodeRuleRepositoy;

        public TReceivingOrderDetailRepository(DFGK_DB context, IMapper mapper, IBarCodeRuleRepository barCodeRuleRepositoy) : base(context, mapper)
        {
            _BarCodeRuleRepositoy = barCodeRuleRepositoy;
        }

        #region 添加入库单弃用
        ///// <summary>
        ///// 添加入库单管理
        ///// </summary>
        ///// <param name="m"></param>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //public bool AddTReceivingOrderDetail(TReceivingOrderDetail m, out string message)
        //{
        //    message = "";
        //    using (var tran = Context.Database.BeginTransaction())
        //        try
        //        {
        //            //货主信息
        //            if (m.OwnerId.HasValue)
        //            {
        //                var depobj = Context.TDepartments.AsQueryable();
        //                var depowobj = Context.TDepartmentOwners.Where(x => x.OwnerId == m.OwnerId);
        //                var owobj = Context.TOwners.Where(x=>x.Status==1);
        //                var delist = (from d in depobj
        //                              join de in depowobj
        //                              on d.Id equals de.DepartmentId
        //                              join o in owobj
        //                              on de.OwnerId equals o.Id
        //                              select d).FirstOrDefault();
        //                if (delist != null)
        //                {
        //                    m.DeptCode = delist.DepartmentCode;
        //                    m.DeptName = delist.DepartmentName;
        //                    var owerobj = owobj.Where(x => x.Id == m.OwnerId).FirstOrDefault();
        //                    if (owerobj != null)
        //                    {
        //                        m.OwnerName = owerobj.Name;
        //                    }
        //                }
        //                else
        //                {
        //                    message = "货主不存在或已被禁用，请先维护";
        //                    return false;
        //                }
        //            }
        //            else
        //            {
        //                m.OwnerId = 0;
        //                m.OwnerName = "";
        //                m.DeptCode = "";
        //                m.DeptName = "";
        //            }

        //            //库房信息
        //            var warehouseobj = Context.TWarehouses.Find(m.WarehouseId);
        //            if (warehouseobj != null && warehouseobj.Status==1)
        //            {
        //                m.WarehouseName = warehouseobj.Name;
        //                m.WarehouseCode = warehouseobj.Code;
        //            }
        //            else
        //            {
        //                message = "仓库不存在或仓库已被禁用，请先维护";
        //                return false;
        //            }
        //            //供应商信息
        //            var supplierobj = Context.TSuppliers.Find(m.SupplierId);
        //            if (supplierobj != null)
        //            {
        //                m.SupplierName = supplierobj.Name;
        //            }
        //            //物料信息
        //            var materialobj = Context.TMaterials.Find(m.MaterialId);
        //            if (materialobj != null)
        //            {
        //                m.MaterialCode = materialobj.Code;
        //                m.MaterialImg = materialobj.Img;
        //                m.MaterialName = materialobj.Name;
        //                m.UnitId = materialobj.UnitId;
        //                m.UnitName = materialobj.UnitName;
        //                m.MaterialTypeCode = materialobj.TypeCode;
        //                m.MaterialTypeName = materialobj.TypeName;
        //                if (materialobj.ExpirationMonth.HasValue && m.ProductDate.HasValue)
        //                {
        //                    m.ExpireDate = m.ProductDate.Value.AddMonths(materialobj.ExpirationMonth.Value);
        //                }
        //            }
        //            //物料批次
        //            TMaterialKey materialKey = null;
        //            var materkeyobj = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == m.BatchNo && x.MaterialId == m.MaterialId);
        //            if (materkeyobj != null)
        //            {
        //                materialKey = materkeyobj;
        //            }
        //            //逻辑分区
        //            var dicobj = Context.TDictItems.FirstOrDefault(x => x.ItemCode == m.LogicalPartCode);
        //            if (dicobj != null)
        //            {
        //                m.LogicalPartName = dicobj.ItemName;
        //            }
        //            //订单来源默认手动创建
        //            m.SourceType = 0;
        //            //质检状态默认为合格
        //            m.QualityState = 1;
        //            m.ReceivedQty = 0;
        //            m.PackagedQty = 0;
        //            m.PackQty = 0;

        //            #region 审计字段
        //            m.CreateUserId = m.NowUserId;
        //            m.CreateUserName = m.NowUserRealName;
        //            m.CreateDate = DateTime.Now;
        //            m.ModifyUserId = m.NowUserId;
        //            m.ModifyUserName = m.NowUserRealName;
        //            m.ModifyDate = DateTime.Now;
        //            m.AuditUserId = m.NowUserId;
        //            m.AuditUserName = m.NowUserRealName;
        //            m.AuditDate = DateTime.Now;
        //            m.SubmitUserId = m.NowUserId;
        //            m.SubmitUserName = m.NowUserRealName;
        //            m.SubmitDate = DateTime.Now;
        //            #endregion
        //            //采购订单行项目类型
        //            m.PurOrderLineType = 0;
        //            m.StackedQty = 0;
        //            if (materialKey == null)
        //            {
        //                TMaterialKey materkeyinsert = new TMaterialKey();
        //                materkeyinsert.BatchNo = m.BatchNo;
        //                materkeyinsert.MaterialId = m.MaterialId;
        //                materkeyinsert.OutFactoryDate = m.OutFactoryDate;
        //                materkeyinsert.OwnerId = m.OwnerId;
        //                materkeyinsert.OwnerName = m.OwnerName;
        //                materkeyinsert.ProduceFactory = m.ProduceFactory;
        //                materkeyinsert.ProductDate = m.ProductDate;
        //                materkeyinsert.Qadate = m.Qadate;
        //                materkeyinsert.SupplierName = m.SupplierName;
        //                materkeyinsert.SupplierId = m.SupplierId;
        //                materkeyinsert.ExpireDate = m.ExpireDate;
        //                materkeyinsert.CreateDate = DateTime.Now;
        //                materkeyinsert.MaterialCode = m.MaterialCode;
        //                materkeyinsert.MaterialName = m.MaterialName;
        //                materkeyinsert.QualityState = m.QualityState;
        //                materkeyinsert.DeptCode = m.DeptCode;
        //                materkeyinsert.DeptName = m.DeptName;
        //                materkeyinsert.Mblnr = m.Mblnr;
        //                materkeyinsert.Mjahr = m.Mjahr;
        //                materkeyinsert.Zeile = m.Zeile;
        //                materkeyinsert.ContractNo = m.ContractNo;
        //                materkeyinsert.PurOrderNo = m.PurOrderNo;
        //                materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
        //                materkeyinsert.PurOrderLineType = m.PurOrderLineType;
        //                materkeyinsert.ProOrderNo = m.ProOrderNo;
        //                materkeyinsert.OutOrderNo = m.OutOrderNo;
        //                Context.TMaterialKeys.Add(materkeyinsert);
        //                int result = Context.SaveChanges();
        //                if (result == 0)
        //                {
        //                    message = "保存失败！";
        //                    tran.Rollback();
        //                    return false;
        //                }
        //                m.MaterialKeyId = materkeyinsert.Id;
        //            }
        //            else
        //            {
        //                m.MaterialKeyId = materialKey.Id;
        //                var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
        //                if (materkey != null)
        //                {
        //                    materkey.BatchNo = m.BatchNo;
        //                    materkey.OutFactoryDate = m.OutFactoryDate;
        //                    materkey.OwnerId = m.OwnerId;
        //                    materkey.OwnerName = m.OwnerName;
        //                    materkey.ProduceFactory = m.ProduceFactory;
        //                    materkey.ProductDate = m.ProductDate;
        //                    materkey.Qadate = m.Qadate;
        //                    materkey.SupplierId = m.SupplierId;
        //                    materkey.SupplierName = m.SupplierName;
        //                    materkey.ExpireDate = m.ExpireDate;
        //                    materkey.MaterialCode = m.MaterialCode;
        //                    materkey.MaterialName = m.MaterialName;
        //                    materkey.QualityState = m.QualityState;
        //                    materkey.DeptCode = m.DeptCode;
        //                    materkey.DeptName = m.DeptName;
        //                    materkey.Mblnr = m.Mblnr;
        //                    materkey.Mjahr = m.Mjahr;
        //                    materkey.Zeile = m.Zeile;
        //                    materkey.ContractNo = m.ContractNo;
        //                    materkey.ProOrderNo = m.ProOrderNo;
        //                    materkey.PurOrderLineNo = m.PurOrderLineNo;
        //                    materkey.PurOrderLineType = m.PurOrderLineType;
        //                    materkey.ProOrderNo = m.ProOrderNo;
        //                    materkey.OutOrderNo = m.OutOrderNo;
        //                    Context.TMaterialKeys.Update(materkey);
        //                }
        //                int result = Context.SaveChanges();
        //                if (result <= 0)
        //                {
        //                    message = "保存失败！";
        //                    tran.Rollback();
        //                    return false;
        //                }
        //            }
        //            Context.TReceivingOrderDetails.Add(m);
        //            int resultt = Context.SaveChanges();
        //            if (resultt > 0)
        //            {
        //                tran.Commit();
        //                return true;
        //            }
        //            tran.Rollback();
        //            return false;

        //        }
        //        catch (Exception)
        //        {
        //            tran.Rollback();
        //            throw;
        //        }
        //}
        #endregion

        /// <summary>
        /// 删除入库单
        /// </summary>
        /// <param name="ordersn"></param>
        /// <returns></returns>
        public bool DelTReceivingOrderDetail(string ordersn)
        {
            var sobj = Context.TReceivingOrderDetails.AsNoTracking().Where(x=>x.OrderSn==ordersn);
            if (sobj.Any())
            {
                Context.TReceivingOrderDetails.RemoveRange(sobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 显示入库单 弃用
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="status"></param>
        /// <param name="warehouseid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TReceivingOrderDetail> GetReceivingOrderDetailList(string orderSn, int billType, int status, int warehouseid, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TReceivingOrderDetails.AsQueryable();
            //入库单号
            if (!string.IsNullOrEmpty(orderSn))
            {
                list = list.Where(x => x.OrderSn.Contains(orderSn));
            }

            if (billType != 0)
            {
                list = list.Where(x => x.BillType == billType);
            }

            if (status < 8)
            {
                list = list.Where(x => x.Status == status);
            }

            if (warehouseid != 0)
            {
                list = list.Where(x => x.WarehouseId == warehouseid);
            }

            totalCount = list.Count();

            list = list.OrderByDescending(x => x.CreateDate);

            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TReceivingOrderDetail GetTReceivingOrderDetailById(int rid)
        {
            return Context.TReceivingOrderDetails.Find(rid);
        }

        /// <summary>
        /// 修改入库单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdTReceivingOrderDetail(TReceivingOrderDetail m, out string message)
        {
            //message = "";
            //using (var tran = Context.Database.BeginTransaction())
            //    try
            //    {
            //        //货主信息
            //        if (m.OwnerId.HasValue)
            //        {
            //            var depobj = Context.TDepartments.AsQueryable();
            //            var depowobj = Context.TDepartmentOwners.Where(x => x.OwnerId == m.OwnerId);
            //            var delist = (from d in depobj
            //                          join de in depowobj
            //                          on d.Id equals de.DepartmentId                                   
            //                          select d).FirstOrDefault();
            //            if (delist != null)
            //            {
            //                m.DeptCode = delist.DepartmentCode;
            //                m.DeptName = delist.DepartmentName;                         
            //            }
            //            else
            //            {
            //                message = "货主不存在或已被禁用，请先维护";
            //                return false;
            //            }
            //        }
            //        else
            //        {
            //            m.OwnerId = 0;
            //            m.OwnerName = "";
            //            m.DeptCode = "";
            //            m.DeptName = "";
            //        }

            //        //库房信息
            //        var warehouseobj = Context.TWarehouses.Find(m.WarehouseId);
            //        if (warehouseobj != null && warehouseobj.Status==1)
            //        {
            //            m.WarehouseName = warehouseobj.Name;
            //            m.WarehouseCode = warehouseobj.Code;
            //        }
            //        else
            //        {
            //            message = "仓库不存在或仓库已被禁用，请先维护";
            //            return false;
            //        }

            //        //TReceivingOrderDetail oldData = null;
            //        //var olddataobj = Context.TReceivingOrderDetails.Find(m.Id);
            //        //if (olddataobj == null) 
            //        //{
            //        //    message = "当前数据可能已被删除，请刷新后再试";
            //        //    return false;
            //        //}
            //        //else
            //        //{
            //        //    if(olddataobj.Status!=0)
            //        //    {
            //        //        message = "只有状态为创建的入库单才能修改";
            //        //        return false;
            //        //    }
            //        //    oldData = olddataobj;
            //        //}
            //        //oldData = olddataobj;
            //        //供应商信息
            //        var supplierobj = Context.TSuppliers.Find(m.SupplierId);
            //        if (supplierobj != null)
            //        {
            //            m.SupplierName = supplierobj.Name;
            //        }
            //        //物料信息
            //        var materialobj = Context.TMaterials.Find(m.MaterialId);
            //        if (materialobj != null)
            //        {
            //            m.MaterialCode = materialobj.Code;
            //            m.MaterialImg = materialobj.Img;
            //            m.MaterialName = materialobj.Name;
            //            m.UnitId = materialobj.UnitId;
            //            m.UnitName = materialobj.UnitName;
            //            m.MaterialTypeCode = materialobj.TypeCode;
            //            m.MaterialTypeName = materialobj.TypeName;
            //            if (materialobj.ExpirationMonth.HasValue && m.ProductDate.HasValue)
            //            {
            //                m.ExpireDate = m.ProductDate.Value.AddMonths(materialobj.ExpirationMonth.Value);
            //            }
            //        }
            //        //物料批次
            //        TMaterialKey materialKey = null;
            //        var materkeyobj = Context.TMaterialKeys.Find(m.MaterialKeyId);
            //        if (materkeyobj == null)
            //        {                     
            //            var materkeyobj2 = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == m.BatchNo && x.MaterialId == m.MaterialId);
            //            if(materkeyobj2!=null)
            //            {
            //                materialKey = materkeyobj2;
            //            }
            //        }
            //        else
            //        {
            //            materialKey = materkeyobj;
            //        }
            //        //逻辑分区
            //        var dicobj = Context.TDictItems.FirstOrDefault(x => x.ItemCode == m.LogicalPartCode);
            //        if (dicobj != null)
            //        {
            //            m.LogicalPartName = dicobj.ItemName;
            //        }                

            //        #region 审计字段
            //        m.ModifyUserId = m.NowUserId;
            //        m.ModifyUserName = m.NowUserRealName;
            //        m.ModifyDate = DateTime.Now;
            //        m.AuditUserId = m.NowUserId;
            //        m.AuditUserName = m.NowUserRealName;
            //        m.AuditDate = DateTime.Now;
            //        #endregion                
            //        if (materialKey == null)
            //        {
            //            TMaterialKey materkeyinsert = new TMaterialKey();
            //            materkeyinsert.BatchNo = m.BatchNo;
            //            materkeyinsert.MaterialId = m.MaterialId;
            //            materkeyinsert.OutFactoryDate = m.OutFactoryDate;
            //            materkeyinsert.OwnerId = m.OwnerId;
            //            materkeyinsert.OwnerName = m.OwnerName;
            //            materkeyinsert.ProduceFactory = m.ProduceFactory;
            //            materkeyinsert.ProductDate = m.ProductDate;
            //            materkeyinsert.Qadate = m.Qadate;
            //            materkeyinsert.SupplierName = m.SupplierName;
            //            materkeyinsert.SupplierId = m.SupplierId;
            //            materkeyinsert.ExpireDate = m.ExpireDate;
            //            materkeyinsert.CreateDate = DateTime.Now;
            //            materkeyinsert.MaterialCode = m.MaterialCode;
            //            materkeyinsert.MaterialName = m.MaterialName;
            //            materkeyinsert.QualityState = m.QualityState;
            //            materkeyinsert.DeptCode = m.DeptCode;
            //            materkeyinsert.DeptName = m.DeptName;
            //            materkeyinsert.Mblnr = m.Mblnr;
            //            materkeyinsert.Mjahr = m.Mjahr;
            //            materkeyinsert.Zeile = m.Zeile;
            //            materkeyinsert.ContractNo = m.ContractNo;
            //            materkeyinsert.PurOrderNo = m.PurOrderNo;
            //            materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
            //            materkeyinsert.PurOrderLineType = m.PurOrderLineType;
            //            materkeyinsert.ProOrderNo = m.ProOrderNo;
            //            materkeyinsert.OutOrderNo = m.OutOrderNo;
            //            Context.TMaterialKeys.Add(materkeyinsert);
            //            int result = Context.SaveChanges();
            //            if (result == 0)
            //            {
            //                message = "保存失败！";
            //                tran.Rollback();
            //                return false;
            //            }
            //            m.MaterialKeyId = materkeyinsert.Id;
            //        }
            //        else
            //        {
            //            m.MaterialKeyId = materialKey.Id;
            //            var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
            //            if (materkey != null)
            //            {
            //                materkey.BatchNo = m.BatchNo;
            //                materkey.OutFactoryDate = m.OutFactoryDate;
            //                materkey.OwnerId = m.OwnerId;
            //                materkey.OwnerName = m.OwnerName;
            //                materkey.ProduceFactory = m.ProduceFactory;
            //                materkey.ProductDate = m.ProductDate;
            //                materkey.Qadate = m.Qadate;
            //                materkey.SupplierId = m.SupplierId;
            //                materkey.SupplierName = m.SupplierName;
            //                materkey.ExpireDate = m.ExpireDate;
            //                materkey.MaterialCode = m.MaterialCode;
            //                materkey.MaterialName = m.MaterialName;
            //                materkey.QualityState = m.QualityState;
            //                materkey.DeptCode = m.DeptCode;
            //                materkey.DeptName = m.DeptName;
            //                materkey.Mblnr = m.Mblnr;
            //                materkey.Mjahr = m.Mjahr;
            //                materkey.Zeile = m.Zeile;
            //                materkey.ContractNo = m.ContractNo;
            //                materkey.ProOrderNo = m.ProOrderNo;
            //                materkey.PurOrderLineNo = m.PurOrderLineNo;
            //                materkey.PurOrderLineType = m.PurOrderLineType;
            //                materkey.ProOrderNo = m.ProOrderNo;
            //                materkey.OutOrderNo = m.OutOrderNo;
            //                Context.TMaterialKeys.Update(materkey);
            //            }
            //            int result = Context.SaveChanges();
            //            if (result <= 0)
            //            {
            //                message = "保存失败！";
            //                tran.Rollback();
            //                return false;
            //            }
            //        }
            //        Context.TReceivingOrderDetails.Update(m);
            //        int resultt = Context.SaveChanges();
            //        if (resultt > 0)
            //        {
            //            tran.Commit();
            //            return true;
            //        }
            //        tran.Rollback();
            //        return false;

            //    }
            //    catch (Exception)
            //    {
            //        tran.Rollback();
            //        throw;
            //    }
            message = "";
            return false;
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdTReceivingOrderDetaState(ReceivingOrderDetailDto m)
        {
            var robj = Context.TReceivingOrderDetails.Find(m.Id);

            if (robj != null)
            {

                switch (robj.Status)
                {
                    case 0:
                        var uobj = Context.TUsers.FirstOrDefault(x => x.Id == m.NowUserId && x.JobNo == m.JobNo);
                        if (uobj != null)
                        {
                            robj.SubmitUserId = m.NowUserId;
                            robj.SubmitUserName = m.NowUserRealName;
                            robj.SubmitDate = DateTime.Now;
                            robj.Remark = m.Remark;
                            //修改为：审核通过
                            robj.Status = 2;
                            Context.TReceivingOrderDetails.Update(robj);
                            break;
                        }
                        return false;

                    case 1:
                        break;

                    case 2:
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：作业中
                        robj.Status = 3;
                        Context.TReceivingOrderDetails.Update(robj);
                        break;

                    case 3:
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：已完成
                        robj.Status = 4;
                        Context.TReceivingOrderDetails.Update(robj);
                        break;

                    default:
                        break;
                }
                return Context.SaveChanges() > 0;
            }
            return false;
        }
        /// <summary>
        /// 导出入库单
        /// </summary>
        /// <returns></returns>
        public List<TReceivingOrderDetail> GetTReceivingOrderDetailExcel()
        {
            try
            {
                return Context.TReceivingOrderDetails.AsQueryable().ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 执行入库作业
        /// </summary>
        /// <returns></returns>
        public bool ExecReceving(TReceivingOrderDetail detail, out string errMsg)
        {

            errMsg = string.Empty;
            TReceivingOrderDetail? orderDetail = detail;

            if (orderDetail.Status != (int)EmBillStatus.Pass)
            {
                // throw new Exception("入库单不存在");
                errMsg = "入库单未审核通过";
                return false;
            }

            orderDetail.Status = (int)EmBillStatus.Executing;
            orderDetail.ModifyDate = DateTime.Now;
            // orderDetail.ModifyUserId = 0;
            // orderDetail.ModifyUserName = "";

            bool result = base.Upd(orderDetail);

            return result;
        }     

        public List<GroupReceivingOrderDto> GetGroupReceivingOrderList(string orderSn, int billType, int status, int warehouseid, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TReceivingOrderDetails.AsQueryable();
            //入库单号
            if (!string.IsNullOrEmpty(orderSn))
            {
                list = list.Where(x => x.OrderSn.Contains(orderSn));
            }

            if (billType != 0)
            {
                list = list.Where(x => x.BillType == billType);
            }

            if (status < 8)
            {
                list = list.Where(x => x.Status == status);
            }

            if (warehouseid != 0)
            {
                list = list.Where(x => x.WarehouseId == warehouseid);
            }
            var groupreceivinglist = new List<GroupReceivingOrderDto>();
            groupreceivinglist = list.GroupBy(x => x.OrderSn).Select(r => new GroupReceivingOrderDto
            {
                OrderSn = r.Key,
                BillType = r.FirstOrDefault().BillType,
                SupplierName=r.FirstOrDefault().SupplierName,
                Remark = r.FirstOrDefault().Remark,               
            }).ToList();
            totalCount = groupreceivinglist.Count();
            return groupreceivinglist;
        }

        /// <summary>
        /// 添加入库单
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool AddTReceivingOrderDetail(GroupReceivingOrderDto m, out string message)
        {
            message = "";
            //判断当前供应商是否存在
            var suppobj = Context.TSuppliers.AsNoTracking().FirstOrDefault(x => x.Code == m.SupplierCode);
            if(suppobj!=null)
            {
                m.SupplierId = suppobj.Id;
                m.SupplierName = suppobj.Name;
                //修改已有的
                suppobj.Name = m.SupplierName;
                suppobj.Contact=m.Contact;
                suppobj.ContactMobile = m.ContactMobile;
                suppobj.ModifyDate=DateTime.Now;
                suppobj.ModifyUserId = m.NowUserId;
                suppobj.ModifyUserName = m.NowUserName;
                Context.TSuppliers.Update(suppobj);
            }
            else
            {
                TSupplier supplier = new TSupplier();
                supplier.Code = m.SupplierCode;
                supplier.Name= m.SupplierName;
                supplier.Contact= m.Contact;
                supplier.ContactMobile= m.ContactMobile;
                supplier.CreateDate= DateTime.Now;
                supplier.CreateUserId = m.NowUserId;
                supplier.CreateUserName = m.NowUserName;
                Context.TSuppliers.Add(supplier);
            }

            foreach (var item in m.childrenReceivingOrders)
            {
                TReceivingOrderDetail receivingOrderDetail = new TReceivingOrderDetail();
                receivingOrderDetail.OrderSn = m.OrderSn;
                receivingOrderDetail.BillType = m.BillType;
                receivingOrderDetail.RelevanceOrderSn = m.RelevanceOrderSn;
                receivingOrderDetail.Agent = m.Agent;
                receivingOrderDetail.SupplierId = m.SupplierId;
                receivingOrderDetail.ProductDate = m.ProductDate;
                receivingOrderDetail.MaterialCategoryId = item.MakerialCategoryId;
                //装备名称
                receivingOrderDetail.MaterialCategoryName = item.MaterialCategoryName;
                receivingOrderDetail.MaterialId = item.MaterialId;
                receivingOrderDetail.MaterialName = item.Name;
                receivingOrderDetail.MaterialCode = item.Code;
                receivingOrderDetail.ModelSpec = item.ModelSpec;
                receivingOrderDetail.QualityState = item.QualityState;//质量等级
                receivingOrderDetail.ReceivedQty = item.ReceivedQty;
                receivingOrderDetail.Qty= item.Qty;
                receivingOrderDetail.TotalPrice = item.ReceivedTotalPrice;
                receivingOrderDetail.Price = item.Price;
                //订单来源默认手动创建
                receivingOrderDetail.SourceType = 0;
                #region 审计字段
                receivingOrderDetail.CreateUserId = m.NowUserId;
                receivingOrderDetail.CreateUserName = m.NowUserName;
                receivingOrderDetail.CreateDate=DateTime.Now;
                #endregion
                Context.TReceivingOrderDetails.Add( receivingOrderDetail);
            }
            return  Context.SaveChanges()>0;
        }

        /// <summary>
        /// 根据入库单编号查询信息
        /// </summary>
        /// <param name="ordersn"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public GroupReceivingOrderDto GetGroupReceivingOrderDtoByOrdersn(string ordersn)
        {
            var receorder = Context.TReceivingOrderDetails.Where(x => x.OrderSn == ordersn);
            if(!receorder.Any())
            {
                return null;
            }
            GroupReceivingOrderDto groupReceivingOrderDto = new GroupReceivingOrderDto();
            groupReceivingOrderDto.OrderSn= receorder.First().OrderSn;
            groupReceivingOrderDto.BillType = receorder.First().BillType;
            groupReceivingOrderDto.RelevanceOrderSn = receorder.First().RelevanceOrderSn;
            groupReceivingOrderDto.Agent=receorder.First().Agent;
            groupReceivingOrderDto.SupplierId = receorder.First().SupplierId;
            groupReceivingOrderDto.SupplierName=receorder.First().SupplierName;
            groupReceivingOrderDto.ProductDate=receorder.First().ProductDate;
            groupReceivingOrderDto.Remark = receorder.First().Remark;

            foreach (var item in receorder)
            {
                ChildrenReceivingOrder childrenReceiving = new ChildrenReceivingOrder();
                childrenReceiving.MakerialCategoryId = item.MaterialCategoryId;
                childrenReceiving.MaterialId=item.MaterialId;
                childrenReceiving.Name = item.MaterialName;
                childrenReceiving.Code = item.MaterialCode;
                childrenReceiving.ModelSpec = item.ModelSpec;
                childrenReceiving.QualityState = item.QualityState;
                childrenReceiving.Price = item.Price;
                childrenReceiving.ReceivedQty= item.ReceivedQty;
                childrenReceiving.Qty=item.Qty;
                childrenReceiving.TotalPrice = item.TotalPrice;
                childrenReceiving.Remark=item.Remark;
                groupReceivingOrderDto.childrenReceivingOrders.Add(childrenReceiving);
            }
            return groupReceivingOrderDto;
        }
    }
}
